package cn.iocoder.yudao.module.ai.controller.admin.operationequ;

import cn.iocoder.yudao.framework.exception.BusinessException;
import cn.iocoder.yudao.module.ai.service.operationendcompany.OperationEndCompanyService;
import cn.iocoder.yudao.module.infra.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.ai.controller.admin.operationequ.vo.*;
import cn.iocoder.yudao.module.ai.dal.dataobject.operationequ.OperationEquDO;
import cn.iocoder.yudao.module.ai.service.operationequ.OperationEquService;

@Tag(name = "管理后台 - 运营中心-算力设备")
@RestController
@RequestMapping("/ai/operation-equ")
@Validated
@Slf4j
public class OperationEquController {

    @Resource
    private OperationEquService operationEquService;
    @Resource
    private OperationEndCompanyService operationEndCompanyService;

//    @PostMapping("/create")
//    @Operation(summary = "创建运营中心-算力设备")
//    @PreAuthorize("@ss.hasPermission('ai:operation-equ:create')")
//    public CommonResult<Long> createOperationEqu(@Valid @RequestBody OperationEquSaveReqVO createReqVO) {
//        return success(operationEquService.createOperationEqu(createReqVO));
//    }
//
//    @PutMapping("/update")
//    @Operation(summary = "更新运营中心-算力设备")
//    @PreAuthorize("@ss.hasPermission('ai:operation-equ:update')")
//    public CommonResult<Boolean> updateOperationEqu(@Valid @RequestBody OperationEquSaveReqVO updateReqVO) {
//        operationEquService.updateOperationEqu(updateReqVO);
//        return success(true);
//    }

//    @DeleteMapping("/delete")
//    @Operation(summary = "删除运营中心-算力设备")
//    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('ai:operation-equ:delete')")
//    public CommonResult<Boolean> deleteOperationEqu(@RequestParam("id") Long id) {
//        operationEquService.deleteOperationEqu(id);
//        return success(true);
//    }

    @GetMapping("/get")
    @Operation(summary = "获得运营中心-算力设备")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:operation-equ:query')")
    public CommonResult<OperationEquRespVO> getOperationEqu(@RequestParam("id") Long id) {
        OperationEquDO operationEqu = operationEquService.getOperationEqu(id);
        OperationEquRespVO respVO = BeanUtils.toBean(operationEqu, OperationEquRespVO.class);
        if(StringUtils.isNotBlank(operationEqu.getCompanyId())){
            respVO.setCompanyName(operationEndCompanyService.getCompanyName(operationEqu.getCompanyId()));
        }
        List< Double> gpuLoadList = new ArrayList<>();
        if(null != operationEqu && StringUtils.isNotBlank(operationEqu.getGpuList())){
            try {
                gpuLoadList = JSONArray.parseArray(operationEqu.getGpuList(), Double.class);
            } catch (Exception e) {
                //
                log.error("解析jsonarray参数异常:"+operationEqu.getId()+","+operationEqu.getGpuList(),e);
            }
        }
        respVO.setGpuLoadList(gpuLoadList);
        return success(respVO);
    }

    @GetMapping("/page")
    @Operation(summary = "获得运营中心-算力设备分页")
    @PreAuthorize("@ss.hasPermission('ai:operation-equ:query')")
    public CommonResult<PageResult<OperationEquRespVO>> getOperationEquPage(@Valid OperationEquSimplePageReqVO simplePageReqVO) {
        OperationEquPageReqVO pageReqVO = new OperationEquPageReqVO();
        org.springframework.beans.BeanUtils.copyProperties(simplePageReqVO, pageReqVO);
        if(StringUtils.isNotBlank(simplePageReqVO.getCompanyId())){
            List<String> ids = operationEndCompanyService.getSelfAndSubCompanyIds(simplePageReqVO.getCompanyId());
            pageReqVO.setCompanyIds(ids);
            if(CollectionUtils.isEmpty(ids)){
                throw new BusinessException("请选择正确的公司");
            }
        }
        if(StringUtils.isNotBlank(simplePageReqVO.getKeyword())){
            pageReqVO.setEquipmentDesc(simplePageReqVO.getKeyword());
        }
        PageResult<OperationEquDO> pageResult = operationEquService.getOperationEquPage(pageReqVO);
        PageResult<OperationEquRespVO> voPage = BeanUtils.toBean(pageResult, OperationEquRespVO.class);
        if(null != voPage && null != voPage.getList()){
            Map<String, String> companyIdAndNameMap = operationEndCompanyService.getCompanyIdAndNameMap(voPage.getList().stream().map(OperationEquRespVO::getCompanyId).collect(Collectors.toList()));
            voPage.getList().forEach(item -> {
                item.setCompanyName(companyIdAndNameMap.get(item.getCompanyId()));
                List< Double> gpuLoadList = new ArrayList<>();
                try {
                    if(StringUtils.isNotBlank(item.getGpuList())){
                        gpuLoadList = JSONArray.parseArray(item.getGpuList(), Double.class);
                    }
                } catch (Exception e) {
                    //
                    log.error("解析jsonarray参数异常:"+item.getId()+","+item.getGpuList(),e);
                }
                item.setGpuLoadList(gpuLoadList);
            });
        }
        return success(voPage);
    }

//    @GetMapping("/export-excel")
//    @Operation(summary = "导出运营中心-算力设备 Excel")
//    @PreAuthorize("@ss.hasPermission('ai:operation-equ:export')")
//    @ApiAccessLog(operateType = EXPORT)
//    public void exportOperationEquExcel(@Valid OperationEquPageReqVO pageReqVO,
//              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
//        List<OperationEquDO> list = operationEquService.getOperationEquPage(pageReqVO).getList();
//        // 导出 Excel
//        ExcelUtils.write(response, "运营中心-算力设备.xls", "数据", OperationEquRespVO.class,
//                        BeanUtils.toBean(list, OperationEquRespVO.class));
//    }

}